package com.ssy.lingxi.product.serviceImpl;

import com.ssy.lingxi.product.common.enums.MaterialProcessEnum;
import com.ssy.lingxi.product.common.enums.MaterialProcessStatusEnum;
import com.ssy.lingxi.product.entity.material.BaseMaterialProcessDO;
import com.ssy.lingxi.product.repository.material.BaseMaterialProcessRepository;
import com.ssy.lingxi.product.service.IProductDataInitService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 彭冬冬
 * @version 2.0.0
 * @date 2022/3/25 17:14
 */
@Service
public class ProductDataInitServiceImpl implements IProductDataInitService {

    @Resource
    private BaseMaterialProcessRepository baseMaterialProcessRepository;

    @Override
    public void initProductServiceData() {
        // 初始化基础物料流程
        initBaseMaterialProcess();
    }

    /**
     * 初始化基础物料流程
     */
    private void initBaseMaterialProcess() {
        // step 1:构建保存数据
        List<BaseMaterialProcessDO> materialProcesses = Arrays.stream(MaterialProcessEnum.values()).map(this::builderBaseMaterialProcessDO).collect(Collectors.toList());
        // step 2:查询数据库存在的基础物料流程
        List<BaseMaterialProcessDO> materialProcessList = baseMaterialProcessRepository.findAll();
        // step 3:整合数据
        materialProcessList.forEach(map -> materialProcesses.stream().filter(f -> f.getProcessKey().equals(map.getProcessKey())).findFirst().ifPresent(p -> {
            map.setCode(p.getCode());
            map.setProcessType(p.getProcessType());
            map.setName(p.getName());
            map.setStatus(p.getStatus());
        }));
        // 剔除数据
        materialProcessList.addAll(materialProcesses.stream().filter(f -> materialProcessList.stream().noneMatch(n -> n.getProcessKey().equals(f.getProcessKey()))).collect(Collectors.toList()));
        baseMaterialProcessRepository.saveAll(materialProcessList);
    }

    private BaseMaterialProcessDO builderBaseMaterialProcessDO(MaterialProcessEnum materialProcessEnum) {
        BaseMaterialProcessDO item = new BaseMaterialProcessDO();
        item.setCode(materialProcessEnum.getCode());
        item.setProcessKey(materialProcessEnum.getProcessKey());
        item.setName(materialProcessEnum.getName());
        item.setProcessType(materialProcessEnum.getType());
        item.setStatus(MaterialProcessStatusEnum.ENABLE.getCode());
        return item;
    }

}
